import 'dart:io';

import '../bean/BadgeBean.dart';
import '../bean/BlockBean.dart';
import '../bean/Challenge.dart';
import '../bean/HashModel.dart';
import 'package:path/path.dart';
import 'package:path_provider/path_provider.dart';
import 'package:sqflite/sqflite.dart';

class DBManager {
  Database? myDatabase;
  String tableName = 'HashModel';
  //挑战
  String challengeTableName = 'challengeTableName';
  //徽章
  String Badge = 'Badge';

  static final DBManager _instance = DBManager._();

  factory DBManager() {
    return _instance;
  }

  DBManager._();

  static Database? _db;

  Future<Database> get db async {
    // if (_db != null) {
    //   return _db;
    // }
    // _db = await _initDB();
    // return _db;
    return _db ??= await initDB();
  }

  Future<Database?> getCheckDatabase() async {
    if (myDatabase != null) return myDatabase;
    myDatabase = await initDB();
    return myDatabase;
  }

  Future<Database> initDB() async {
    Directory directory = await getApplicationDocumentsDirectory();
    String path = join(directory.path, 'MYDB.db'); //数据库名称
    print(path);
    return await openDatabase(path, version: 1, onOpen: (db) {},
        onCreate: (Database db, int v) async {
      //建表
      print("开始建表"); //TEXT
      await db.execute(
          "CREATE TABLE $tableName(id INTEGER PRIMARY KEY AUTOINCREMENT, onclickPositon INTEGER,type INTEGER)");
      await db.execute(
          "CREATE TABLE $challengeTableName(id INTEGER PRIMARY KEY AUTOINCREMENT, time INTEGER,type INTEGER)");
      await db.execute(
          "CREATE TABLE $Badge(id INTEGER PRIMARY KEY AUTOINCREMENT, time INTEGER,img TEXT)");
    });
  }

  Future<List> getDBInfo(int type) async {
    List<HashModel> res = [];
    final Database? databaseDB = await getCheckDatabase();
    // List getRes =  await databaseDB!.query("SELECT * FROM $tableName ORDER BY id DESC");
    //List getRes =  await databaseDB!.query(tableName);
    var getRes = await databaseDB!
        .rawQuery('SELECT * FROM $tableName WHERE type=${type}');
    res = getRes.map<HashModel>((e) => HashModel.fromJson(e)).toList();
    print("res:${res.length}");
    return res;
  }

  /**
   * 获取当月的日历情况
   */
  Future<List> getDBChall(int time) async {
    List<Challenge> res = [];
    final Database? databaseDB = await getCheckDatabase();
    // int res = await databaseDB!.insert(tableName, user.toJson());
    var getRes = await databaseDB!
        .rawQuery('SELECT * FROM $challengeTableName WHERE time>=${time}');
    res = getRes.map<Challenge>((e) => Challenge.fromJson(e)).toList();
    return res;
  }

  /**
    * 获取所有的
    */
  Future<List> getDBAllChall() async {
    List<Challenge> res = [];
    final Database? databaseDB = await getCheckDatabase();
    // int res = await databaseDB!.insert(tableName, user.toJson());
    var getRes =
        await databaseDB!.rawQuery('SELECT * FROM $challengeTableName');
    res = getRes.map<Challenge>((e) => Challenge.fromJson(e)).toList();
    return res;
  }

  Future<List<BadgeBean>> getDBBadge() async {
    List<BadgeBean> res = [];
    final Database? databaseDB = await getCheckDatabase();
    // int res = await databaseDB!.insert(tableName, user.toJson());
    var getRes = await databaseDB!.rawQuery('SELECT * FROM $Badge');
    res = getRes.map<BadgeBean>((e) => BadgeBean.fromJson(e)).toList();
    return res;
  }

  // 获取
  // Future<List<HashModel>> getAll() async {
  //   List<HashModel> res = [];
  //   final Database? databaseDB = await getCheckDatabase();
  //   List getRes = await databaseDB!.query(tableName);
  //   res = getRes.map<HashModel>((e) =>HashModel.fromJson(e)).toList();
  //   return res;
  // }

  insertHashModel(HashModel user) async {
    final Database? databaseDB = await getCheckDatabase();
      await databaseDB!.insert(tableName, user.toJson());
//  _database.rawInsert("INSERT INTO")
  }

  insertChallenge(Challenge user) async {
    final Database? databaseDB = await getCheckDatabase();
    int res = await databaseDB!.insert(challengeTableName, user.toJson());
  }

  insertBadge(BadgeBean user) async {
    final Database? databaseDB = await getCheckDatabase();
    int res = await databaseDB!.insert(Badge, user.toJson());
  }

  // 更新表操作
  updataTableRaw(List<List<BlockBean>> bean) async {
    final Database? databaseDB = await getCheckDatabase();

    // await db.update(table, row, where: '$columnId = ?', whereArgs: [id]);

    for (int i = 0; i < bean.length; i++) {
      for (int j = 0; j < bean.length; j++) {
        print("循环的ID:${bean[i][j].id}");
        databaseDB!.rawUpdate(
            "UPDATE $tableName SET img = ${bean[i][j].img}, defaultImg = ${bean[i][j].defaultImg}, normal = ${bean[i][j].normal}, eliminationEffect = ${bean[i][j].eliminationEffect}  WHERE id = ${bean[i][j].id}");
      }
    }
    // int res = await databaseDB!.rawUpdate(
    //     "UPDATE $tableName SET name = ${user.name}, author = ${user.height}  WHERE id = ${user.id}");
  }

  // // 更新
  // updataUser(BlockBean user) async {
  //   final Database? databaseDB = await getCheckDatabase();
  //   int res = await databaseDB!
  //       .update(tableName, user.toJson(), where: "id = ${user.id}");
  //   print('执行结果$res');
  // }

  Future<int> deleteTableRaw(List<List<BlockBean>> bean,
      {String sqlStr = "DELETE FROM blockBean"}) async {
    final Database? databaseDB = await getCheckDatabase();
    int res = await databaseDB!.rawDelete(sqlStr, bean);
    //  .rawDelete("DELETE FROM $tableName WHERE id = $userId");
    return res;
  }

  deletaHashModelAll(int type) async {
    final Database? databaseDB = await getCheckDatabase();
    await databaseDB!.delete(tableName, where: 'type = ?', whereArgs: [type]);
    // int res = await databaseDB!.delete("DELETE FROM $tableName WHERE type = ${type}");
    // print('执行结果$res');
  }

  deletaChallenge(int type) async {
    final Database? databaseDB = await getCheckDatabase();
    await databaseDB!
        .delete(challengeTableName, where: 'type = ?', whereArgs: [type]);
    // int res = await databaseDB!.delete("DELETE FROM $tableName WHERE type = ${type}");
    // print('执行结果$res');
  }

  // deletaUser(int userId) async {
  //   final Database? databaseDB = await getCheckDatabase();
  //   int res = await databaseDB!.delete(tableName, where: "id = $userId");
  //  // print('执行结果$res');
  // }
}
